package com.farsunset.webhook.controller.lvxin;

import com.farsunset.webhook.model.PubMenuEvent;
import com.farsunset.webhook.service.RobotChatService;
import org.apache.commons.io.IOUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 侣信公众号webhook实现
 */
@RestController
public class AccountController {

	private static final String TEXT_BODY = "{\"contentType\":0,\"code\":200,\"content\":\"%s\"}";

	@Resource
	private RobotChatService robotChatService;
	
	@PostMapping(value = "/handle",produces = {MediaType.APPLICATION_JSON_VALUE})
	public String handle(@RequestBody PubMenuEvent event) throws Exception {
		if (event.eventType.equals(PubMenuEvent.EVENT_TYPE_SUBSCRIBE)) {
			return doOnSubscribeEvent(event);
		}

		if (event.eventType.equals(PubMenuEvent.EVENT_TYPE_UNSUBSCRIBE)) {
			return doOnUnSubscribeEvent(event);
		}

		if (event.eventType.equals(PubMenuEvent.EVENT_TYPE_TEXT)) {
			return doOnReceivedTextEvent(event);
		}

		if (event.eventType.equals(PubMenuEvent.EVENT_TYPE_MENU)) {
			return doOnMenuEvent(event);
		}

		return "{\"code\":403,\"message\":\"未知的事件:" + event.eventType + "\"}";
	}

	private String doOnReceivedTextEvent(PubMenuEvent event) throws Exception {

		String text = robotChatService.get(event.text,event.account);

		if (text != null){
			return String.format(TEXT_BODY,text);
		}

		return IOUtils.toString(getClass().getResourceAsStream("/response/text.txt"), StandardCharsets.UTF_8);
	}

	private String doOnMenuEvent(PubMenuEvent event) throws IOException {
		if (event.menuCode.equals("KEY_SUB_NEWS")) {
			return IOUtils.toString(getClass().getResourceAsStream("/response/news.txt"),StandardCharsets.UTF_8);
		}
		if (event.menuCode.equals("KEY_SUB_ARTICLE")) {
			return IOUtils.toString(getClass().getResourceAsStream("/response/article.txt"),StandardCharsets.UTF_8);
		}
		return null;
	}

	private String doOnSubscribeEvent(PubMenuEvent event) {
		// TODO 处理取消订阅的逻辑
		return "{\"code\":200}";
	}

	private String doOnUnSubscribeEvent(PubMenuEvent event) {
		// TODO 处理订阅的逻辑
		return "{\"code\":200}";
	}
}
